<?php

namespace App\Http\Controllers\V1\BusinessData;

use App\Http\Requests\V1\CollectDataRequest;
use App\Http\Requests\V1\TransformerRequest;
use App\Models\V1\BasicCircuits;
use App\Models\V1\BasicCollectors;
use App\Models\V1\BasicCollectTransformers;
use App\Models\V1\BasicCustomers;
use App\Models\V1\BasicTransformers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use League\Flysystem\Exception;
use Log;
use DB;

class CollectDataController extends Controller
{
    /**
     * 显示数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data['customers'] = $this->getCustomersList();
        $data['transformers'] = $this->getTransformersList();
        return view('v1.collect_datas',$data);
    }


    /**
     * 获取数据 所有的回路，展示回路最新的采集数据
     *
     * @param Request $request
     */
    public function postCircuitsIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');
        $customer_code = $request->input('customer_code');
        $transformer_code = $request->input('transformer_code');

        // 获取符合查询条件的数据
        $data = $this->getCircuitDataList($currentPage, $rows, $keywords,$customer_code,$transformer_code);
        if (!$data->isEmpty()) {

            $formatList = array();

            $count = $data->total() > 0 ? $data->total() : 0;

            if ($count > 0) {

                // 格式化数据
                foreach ($data->items() as $item) {
                    $collectorData = $this->getAlarmDataByCode($item['code']);
                    $collectDatas = $item->collectDatas;// 该回路下所有的采集数据
                    $tempCount = count($collectDatas);
                    $collectorObj  = $this->getCollectorByCode($item['collector_code']);
                    $transformerObj = $this->getTransformerByCode($collectorObj['transformer_code']);
                    $customerObj = $this->getCustomerByCode($transformerObj['customer_code']);
                    $formatItem['code'] = $item['code']; // 回路编码
                    $formatItem['name'] = $tempCount > 1 ? $item['name'].'（'.$tempCount.'）' : $item['name'];
                    $formatItem['customer_name'] = $customerObj['name']; // 客户名称
                    $formatItem['device_name'] = $transformerObj['model_code'];//变压器客户编码
                    $formatItem['device_address'] = $transformerObj['address'];
                    $formatItem['collector_code'] = $collectorObj['code'];// 采集器编码
                    $formatItem['collector_mac_code'] = $collectorObj['mac_code']; // 采集器mac地址
                    $formatItem['temperature'] = $this->formatCollectData($collectorData['temperature']);
                    $formatItem['voltage'] = $this->formatCollectData($collectorData['voltage']);
                    $formatItem['electric'] = $this->formatCollectData($collectorData['electric']);
                    $formatItem['state'] =  $this->formatCollectState($item['state']);
                    $formatItem['process_state'] = $this->formatProcessState($collectorData['process_state']);
                    $formatItem['updated_at'] = $collectorData['updated_at']->format('Y-m-d H:i');
                    $formatItem['created_at'] = $collectorData['created_at']->format('Y-m-d H:i');

                    array_push($formatList, $formatItem);
                }

                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }

        return $response;
    }

    /**
     *
     * 获取数据 回路详情中回路所有的采集数据列表
     *
     * @param Request $request
     */
    public function postCollectDataIndex(Request $request)
    {
        $circuit_code = $request->input('code');
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');

        // 获取符合查询条件的数据
        $data = $this->getCollectDataList($circuit_code,$currentPage, $rows, $keywords);

        if (!$data->isEmpty()) {

            $formatList = array();

            $count = $data->total() > 0 ? $data->total() : 0;

            if ($count > 0) {
                $type = '1'; // type:1 电压、电流、温度 显示数字 type:2 显示灯泡图片
                // 格式化数据
                foreach ($data->items() as $item) {
                    $circuitObj = $item->circuit;
                    $collectorObj  = $this->getCollectorByCode($circuitObj['collector_code']);
                    $transformerObj = $this->getTransformerByCode($collectorObj['transformer_code']);
                    $formatItem['code'] = $item['code'];
                    $formatItem['name'] = $circuitObj['name'];
                    $formatItem['device_name'] = $transformerObj['model_code'];
                    $formatItem['device_address'] = $transformerObj['address'];
                    $formatItem['collector_code'] = $collectorObj['code'];
                    $formatItem['collector_mac_code'] = $collectorObj['mac_code'];
                    $formatItem['temperature'] = $this->formatCollectData($item['temperature'],$type);
                    $formatItem['voltage'] = $this->formatCollectData($item['voltage'],$type);
                    $formatItem['electric'] = $this->formatCollectData($item['electric'],$type);
                    $formatItem['state'] =  $this->formatCollectState($circuitObj['state']);
//                    $formatItem['process_state'] = $this->formatProcessState($item['process_state']);
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i');
                    array_push($formatList, $formatItem);
                }

                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }

        return $response;
    }

//    /**
//     * 获取数据 所有的报警数据，同一个回路多个报警展示最新的一条
//     *
//     * @param Request $request
//     */
//    public function postAlarmIndex(Request $request)
//    {
//        $response = [
//            'code' => 1,
//            'msg' => '',
//            'count' => 0,
//            'data' => [],
//        ];
//
//        // 获取符合查询条件的数据
//        $currentPage = $request->get('page');
//        $rows = $request->get('limit');
//        $keywords = $request->get('keywords');
//
//        // 获取符合查询条件的数据
//        $data = $this->getAlarmCircuitList($currentPage, $rows, $keywords);
//        if (!$data->isEmpty()) {
//
//            $formatList = array();
//
//            $count = $data->total() > 0 ? $data->total() : 0;
//
//            if ($count > 0) {
//                // 格式化数据
//                foreach ($data->items() as $item) {
//                    $collectorData = $this->getAlarmDataByCode($item['code']);
//                    $collectDatas = $item->collectDatas;// 该回路下所有的采集数据
//                    $tempCount = count($collectDatas);
//                    $collectorObj  = $this->getCollectorByCode($item['collector_code']);
//                    $transformerObj = $this->getTransformerByCode($collectorObj['transformer_code']);
//                    $formatItem['code'] = $collectorData['code'];
//                    $formatItem['name'] = $tempCount > 1 ? $item['name'].'（'.$tempCount.'）' : $item['name'];
//                    $formatItem['device_name'] = $transformerObj['model_code'];
//                    $formatItem['device_address'] = $transformerObj['address'];
//                    $formatItem['collector_code'] = $collectorObj['code'];
//                    $formatItem['collector_mac_code'] = $collectorObj['mac_code'];
//                    $formatItem['temperature'] = $this->formatCollectData($collectorData['temperature']);
//                    $formatItem['voltage'] = $this->formatCollectData($collectorData['voltage']);
//                    $formatItem['electric'] = $this->formatCollectData($collectorData['electric']);
//                    $formatItem['state'] =  $this->formatCollectState($item['state']);
//                    $formatItem['process_state'] = $this->formatProcessState($collectorData['process_state']);
//                    $formatItem['updated_at'] = $collectorData['updated_at']->format('Y-m-d H:i');
//                    $formatItem['created_at'] = $collectorData['created_at']->format('Y-m-d H:i');
//                    array_push($formatList, $formatItem);
//                }
//
//                $response['code'] = 0;
//                $response['msg'] = '加载数据成功';
//                $response['count'] = $count;
//                $response['data'] = $formatList;
//            }
//        }
//
//        return $response;
//    }

    /**
     * 进入单条数据显示界面 (适用于新增addData、查看viewData、编辑editData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $data['view'] = $request->input('view');
        $data['code'] = $request->input('code');
        $collectData = $this->getCollectDataByCode($data['code']);
        $circuitObj = $this->getCircuitByCode($collectData['circuit_code']);
        $collectorObj  = $this->getCollectorByCode($circuitObj['collector_code']);
        $transformerObj = $this->getTransformerByCode($collectorObj['transformer_code']);
        switch ($request->input('view')){
            case 'editData':
                $data['device_code'] = $transformerObj['model_code'];
                $data['device_address'] = $transformerObj['address'];
                $collectData['state'] = $circuitObj['state'] === 1 ? '正常' : '异常';
                $data['itemData'] = $collectData;
                return view('v1.form.collect_datas_item', $data);
                break;
            case 'viewData':
                $data['device_code'] = $transformerObj['model_code'];
                $data['device_address'] = $transformerObj['address'];
                $collectData['state'] = $circuitObj['state'] === 1 ? '正常' : '异常';
                $data['itemData'] = $collectData;
                return view('v1.form.collect_datas_item', $data);
                break;

        }
    }

//    /**
//     * 显示数据导入页面
//     *
//     * @param Request $request
//     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
//     */
//    public function importView(Request $request)
//    {
//        // 获取登录用户
//        $loginUser = Auth::user();
//
//        $data['view'] = $request->input('view');
//        $data['code'] = $loginUser->getAttribute('code');
//
//        return view('v1.form.upload_excel', $data);
//    }

    /**
     * 更新基本信息(单元格)
     *
     * @param TransformerRequest $request
     * @return array
     */
    public function updateCellData(TransformerRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '采集数据代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateCollectData($request);

            // 更新采集数据信息
            $successFlag = $this->handleUpdate($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '采集数据代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 更新基本信息
     *
     * @param CollectDataRequest $request
     * @return array
     */
    public function updateData(CollectDataRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '采集数据代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateCollectData($request);

            // 更新采集数据信息
            $successFlag = $this->handleUpdate($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '采集数据代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }


    /**
     * 删除基本信息
     *
     * @param CollectDataRequest $request
     * @return array
     */
    public function deleteData(CollectDataRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '采集数据代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateCollectData($request);

            // 删除采集数据信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '采集数据代码[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除采集数据基本信息
     *
     * @param CollectDataRequest $request
     * @return array
     */
    public function deleteBatchData(CollectDataRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '采集数据批量删除失败！',
        ];

        if ($request->method() === 'POST') {

            // 删除采集数据信息
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '采集数据批量删除成功！';
            }
        }

        return $response;
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的所有回路数据列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @param $customer_code 客户代码
     * @param $transformer_code 变压器代码
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getCircuitDataList($page = 1, $rows, $keywords,$customer_code,$transformer_code)
    {
        $collectorList = array();
        $isSelect = false; // 是否选择了条件
        //判断是否选择了客户
        if (!empty($customer_code)) {
            $isSelect = true;
            // 获取该客户的变压器
            $transformer_codes = BasicTransformers::where('customer_code',$customer_code)->pluck('code')->unique()->toArray();
            // 是否选择了变压器
            if (!empty($transformer_code)){
                $isin = in_array($transformer_code,$transformer_codes);
                if ($isin){

                    $transformer_codes = array();
                    array_push($transformer_codes,$transformer_code);
                }else{
                    $transformer_codes = array();
                }
            }
            foreach ($transformer_codes as $code){
                // 变压器与采集器 一对一
                $collectorObj= BasicCollectors::where('transformer_code',$code)->first();
                $collector_code = $collectorObj['code'];
                array_push($collectorList,$collector_code);

            }
        }else{
            if (!empty($transformer_code)){
                $isSelect = true;
                $collectorList = BasicCollectors::where('transformer_code',$transformer_code)->pluck('code')->unique()->toArray();
            }
        }

        // 先找出有采集数据的回路
        $circuit_codes = BasicCollectTransformers::pluck('circuit_code')->unique()->toArray();
        // 找出回路
        if (!isset($keywords) || empty($keywords)) {
            if ($isSelect){
                $data = BasicCircuits::whereIn('code',$circuit_codes)
                    ->whereIn('collector_code',$collectorList)
                    ->orderBy('created_at', 'desc')
                    ->paginate($rows, ['*'], 'page', $page);
            }else{
                $data = BasicCircuits::whereIn('code',$circuit_codes)
                    ->orderBy('created_at', 'desc')
                    ->paginate($rows, ['*'], 'page', $page);
            }

        } else {
            if ($isSelect){
                $data = BasicCircuits::where('name', 'like', '%' . $keywords . '%')
                    ->whereIn('code',$circuit_codes)
                    ->whereIn('collector_code',$collectorList)
                    ->orderBy('created_at', 'desc')
                    ->paginate($rows, ['*'], 'page', $page);
            }else{
                $data = BasicCircuits::where('name', 'like', '%' . $keywords . '%')
                    ->whereIn('code',$circuit_codes)
                    ->orderBy('created_at', 'desc')
                    ->paginate($rows, ['*'], 'page', $page);
            }

        }

        return $data;
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询指定回路的所有采集数据列表
     *
     * @param $circuit_code 回路代码
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getCollectDataList($circuit_code,$page = 1, $rows, $keywords)
    {
        if (!isset($keywords) || empty($keywords)) {
            $data = BasicCollectTransformers::where('circuit_code',$circuit_code)
                ->orderBy('created_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = BasicCollectTransformers::where('circuit_code',$circuit_code)
                ->where('name', 'like', '%' . $keywords . '%')
                ->orderBy('created_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }

    /**
     * 获取所有的客户列表信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getCustomersList()
    {
        $data = BasicCustomers::get(['code', 'name']);
        return $data;
    }

    /**
     * 获取所有的变压器列表数据
     *
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getTransformersList()
    {
        $data = BasicTransformers::get(['code', 'model_code']);
        return $data;
    }

    /**
     * 根据回路代码获取该回路最新的采集数据
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getAlarmDataByCode($code)
    {
        $data = BasicCollectTransformers::where('circuit_code',$code)->orderBy('created_at', 'desc')->first();
        return $data;
    }

    /**
     * 根据采集数据代码获取对应采集数据信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getCollectDataByCode($code)
    {
        $data = BasicCollectTransformers::where('code', $code)->first();
        return $data;
    }



    /**
     * 根据采集数据代码获取对应变压器信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getTransformerByCode($code)
    {
        $transformer = BasicTransformers::where('code', $code)->first();
        return $transformer;
    }

    /**
     * 根据回路代码获取回路信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getCircuitByCode($code)
    {
        $data = BasicCircuits::where('code',$code)->first();
        return $data;
    }

    /**
     * 根据采集器代码获取采集器信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getCollectorByCode($code)
    {
        $data = BasicCollectors::where('code',$code)->first();
        return $data;
    }

    /**
     * 根据客户代码获取客户信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getCustomerByCode($code)
    {
        $data = BasicCustomers::where('code',$code)->first();
        return $data;
    }


    /**
     * 格式化显示内容类型
     *
     * @param $val
     * @return string
     */
    private function formatProcessState($val)
    {
        $strFormat = '<span>未知</span>';
        switch ($val) {
            case 0:
                $strFormat = '<span>未处理</span>';
                break;
            case 1:
                $strFormat = '<span>已处理</span>';
                break;
            case 2:
                $strFormat = '<span>处理中</span>';
                break;
        }
        return $strFormat;
    }

    /**
     * 格式化显示内容类型
     *
     * @param $val
     * @return string
     */
    private function formatCollectState($val)
    {
        $strFormat = '<span>未知</span>';
        switch ($val) {
            case 0:
                $strFormat = '<div style=" position: absolute;left: 45%;top: 40%;height:10px;width:10px;border-radius: 5px;background-color: #f53b39;text-align: center; "></div>';
                break;
            case 1:
                $strFormat = '<div style=" position: absolute;left: 45%;top: 40%;height:10px;width:10px;border-radius: 5px;background-color: #23df28;text-align: center; "></div>';
                break;
        }
        return $strFormat;
    }

    /**
     * 格式化显示内容类型
     *
     * @param $val
     * @return string
     */
    private function formatCollectData($val)
    {
        if ($val > 30){
            $strFormat = '<p style="color: #f53b39">' .$val.'</p>';
        }else if($val > 20){
            $strFormat = '<p style="color: #fef04b">' .$val.'</p>';
        }
        else{
            $strFormat = '<p>'.$val.'</p>';
        }
        return $strFormat;
    }


    ///////////////////////////////////////////////////////////////////
    /// 验证表单请求功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新采集数据信息验证请求
     *
     * @param Request $request
     */
    private function validateCollectData(Request $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新采集数据信息
     *
     * @param Request $request
     * @param bool $bCell 是否为单元格修改数据
     * @return bool
     */
    private function handleUpdate(Request $request, $bCell)
    {
        $where = $request->input('code');

        // 拼装更新数据数组
        $updateData = array();
        if ($bCell) { // 单元格修改
            $attrs = $request->input('attrs');
            $values = $request->input('values');
            $counter = 0;
            foreach ($attrs as $attr) {
                $updateData[$attr] = $values[$counter];
                $counter++;
            }
        } else { // 表单修改
            // 拼装更新数据数组
            // 处理人
             if ($request->input('handler') !== "") {
                 $updateData['handler'] = $request->input('handler');
             }
            // 处理状态 process_state:2 处理中
            $updateData['process_state'] = 2;

        }

        DB::beginTransaction(); // 开启事务
        $successFlag = false;
        try{
            // 更新采集数据信息
            $rspObj = BasicCollectTransformers::where('code', $where)
                ->update($updateData);
            $successFlag = $rspObj;

            if (!$successFlag){
                DB::rollBack();
            }else{
                DB::commit();
            }
            return $successFlag;
        }catch (Exception $exception){
            DB::rollback();
            return $successFlag;
        }
    }

    /**
     * 处理更新采集数据信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        $where = $request->input('code');

        if ($bBatch) { // 批量删除
            $codeList = $request->input('code');

            foreach ($codeList as $code) {
                $rspObj = BasicCollectTransformers::where('code', $code)->delete();
            }
        } else { // 单条删除
            $rspObj = BasicCollectTransformers::where('code', $where)
                ->delete();
        }

        return $rspObj;
    }


}
